package sk.tuke.android4all.dialer;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnGenericMotionListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import sk.tuke.android4all.controls.CustomFragment;
import sk.tuke.android4all.listeners.SwipeListener;
import sk.tuke.android4all.services.Tts;

public class ContextmenuFragment extends CustomFragment {

		private static String TAG = "ContextmenuFragment";	
		private ContactInfo mContact = null;
		private Activity mActivity = null;
		private String selectedTag = null;
		int touchCounter = 0;
		private final int TOUCH_INTENSITY = 4;
		private SwipeListener mActionListener = null;
		private Tts mSpeechEngine;// TODO Auto-generated method stub

		
		public ContextmenuFragment(Activity aActivity_in, ContactInfo aContact_in){
			this.mActivity = aActivity_in;
			mContact = aContact_in;
			mSpeechEngine = new Tts(mActivity);
		}
		
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
		        Bundle savedInstanceState) {
			View rootView = null;
			if(mContact != null){
				rootView = inflater.inflate(R.layout.fragment_contextmenu, container, false);	
			}else{
				rootView = inflater.inflate(R.layout.fragment_contextmenu_noitem, container, false);	
			}
		    
		    return rootView;
		}
		
		@Override
		public void onActivityCreated(Bundle savedInstanceState) {
		    super.onActivityCreated(savedInstanceState);
		   createUI();
		}
		
		private void createUI() {
			mActionListener =  new SwipeListener(mActivity) {
		        @Override
		        public void onDoubleTapAction(int count) {
		            Log.i("TAG", "DoubleTapped " + selectedTag);
		            resetTouchCounter();
		            if(selectedTag != null){
		            	if(selectedTag == getResources().getString(R.string.fragmentcontext_call)){
		            		invokeCall();
		            	}else if(selectedTag == getResources().getString(R.string.fragmentcontext_message)){
		            		invokeMessage();
		            	}else if(selectedTag == getResources().getString(R.string.fragmentcontext_edit)){
		            		invokeEdit();
		            	}else if(selectedTag == getResources().getString(R.string.fragmentcontext_delete)){
		            		invokeDelete();
		            	}else if(selectedTag == getResources().getString(R.string.fragmentcontext_new)){
		            		invokeNew();
		            	}
		            }
		        }
		
				@Override
				public void onZoomInAction() {
					// TODO Auto-generated method stub
					
				}
		
				@Override
				public void onZoomOutAction() {
					// TODO Auto-generated method stub
					
				}
			};
			getView().setOnTouchListener(mActionListener);
			
			if(mContact != null){
				setControl(R.id.fragmentcontext_call);
				setControl(R.id.fragmentcontext_message);
				setControl(R.id.fragmentcontext_edit);
				setControl(R.id.fragmentcontext_delete);
			}
			setControl(R.id.fragmentcontext_new);
		}
		
		private void setControl(int controlId) {
			final TextView controlTv = (TextView) getView().findViewById(controlId);
			controlTv.setOnGenericMotionListener(new OnGenericMotionListener(){
		
				@Override
				public boolean onGenericMotion(View arg0, MotionEvent arg1) {
					mActionListener.resetTouchCounter();
					String textInControl = controlTv.getText().toString();
		            if (selectedTag != textInControl && touchCounter>TOUCH_INTENSITY) {
		                touchCounter = 0;
		                mSpeechEngine.sayMessage(textInControl);
		                selectedTag = controlTv.getText().toString();
		            }else{
		                touchCounter++;
		            }
		            return false;
				}});		
		}
		
		@Override
		public void returnAction() {
			mSpeechEngine.sayMessage(getResources().getString(R.string.fragmentcontacts_intro));
			mActivity.getFragmentManager().beginTransaction().replace(R.id.container, new ContactsFragment(mActivity), ContactsFragment.class.getName()).commit();
		}
		
		private void invokeNew() {
			mSpeechEngine.sayMessage(getResources().getString(R.string.fragmentcontext_new));
			mActivity.getFragmentManager().beginTransaction().replace(R.id.container, new NewContactFragment(mActivity, null), NewContactFragment.class.getName()).commit();
		}

		private void invokeDelete() {
			mSpeechEngine.sayMessage(getResources().getString(R.string.fragmentcontext_delete));	
			deleteContact(mContact.getName(), mContact.getNumber());
			mActivity.getFragmentManager().beginTransaction().replace(R.id.container, new ContactsFragment(mActivity), ContactsFragment.class.getName()).commit();
		}

		private void invokeEdit() {
			mSpeechEngine.sayMessage(getResources().getString(R.string.fragmentcontext_edit));
			mActivity.getFragmentManager().beginTransaction().replace(R.id.container, new NewContactFragment(mActivity, mContact), NewContactFragment.class.getName()).commit();
		}

		private void invokeMessage() {
			mSpeechEngine.sayMessage(getResources().getString(R.string.fragmentcontext_message));
			Intent sendIntent = new Intent(Intent.ACTION_VIEW);         
			sendIntent.setData(Uri.parse("sms:" + mContact.getNumber().toString()));
			mActivity.startActivity(sendIntent);
		}

		private void invokeCall() {
			mSpeechEngine.sayMessage(getResources().getString(R.string.fragmentcontext_call));
			String callingNumber = "tel:" + mContact.getNumber().toString();
    		Intent intent = new Intent(Intent.ACTION_CALL);
    		intent.setData(Uri.parse(callingNumber));
    		startActivity(intent);
		}
		
		private void deleteContact(String aName_in, String aNumber_in) {
	        Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(aNumber_in));
	        Cursor cursor = mActivity.getApplicationContext().getContentResolver().query(contactUri, null, null, null, null);
	        try {
	            if (cursor.moveToFirst()) {
	                do {
	                    if (cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME)).equalsIgnoreCase(aName_in)) {
	                        String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
	                        Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
	                        mActivity.getApplicationContext().getContentResolver().delete(uri, null, null);
	                    }

	                } while (cursor.moveToNext());
	            }

	        } catch (Exception ex) {
	            Log.e(TAG, ex.getMessage());
	        }
	    }

}
